
/**
 * @description: 图片压缩
 * @param {*} img
 * @return {*}
 */

export const compressImg = (file) => {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    img.onload = () => {
      const MAX_WIDTH = 1600; // 最大宽度设置为1600px，可根据需要调整
      let width = img.width;
      let height = img.height;
      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_WIDTH) {
          width *= MAX_WIDTH / height;
          height = MAX_WIDTH;
        }
      }
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);
      canvas.toBlob((blob) => {
        resolve(new File([blob], file.name, { type: file.type })); // 返回新的压缩文件对象
      }, 'image/jpeg', 0.7); // 压缩质量为0.7（可调）
    };
    img.src = URL.createObjectURL(file); // 设置图片源为File对象URL，以便加载到img元素中以获取尺寸信息。
  });
  }
  